package com.rui.study.algorithm.T_Java的引用和ThreadLocal那些事儿;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

public class SoftReferenceTEst {

    public static final int _1MB = 1024 * 1024;

    /**
     * 软引用的示例
     * 启动参数：-Xms10m -Xmx10m -XX:+PrintGCDetails
     * @param args
     */
    public static void main(String[] args) {
        ReferenceQueue queue = new ReferenceQueue();
        SoftReference softReference = new SoftReference(new User("yaowenrui", 27), queue);

        System.gc();
        System.out.println("内存充足时，触发gc：" + softReference.get());
        System.out.println("内存充足时，触发gc：" + queue.poll());

        // 填满内存
        fillHeap();

        System.out.println("内存不足时，触发gc：" + softReference.get());
        System.out.println("内存不足时，触发gc：" + queue.poll());
    }

    private static void fillHeap() {
        SoftReference softReference1 = new SoftReference(new byte[5 * _1MB]);
        byte[] allocation = new byte[5 * _1MB];
    }
}
